import 'package:dio/dio.dart';
import 'package:dustbin_sort/model/user_profile_entity.dart';
import 'package:dustbin_sort/util/navigator_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginScreen extends StatelessWidget {
	static const routeName = '/auth';
	static const LOGIN_URL = "http://127.0.0.1:8888/auth/login";

	Future<String> _login(username,password) async{

		try{
			Dio dio = new Dio();

			Response response = await dio.post(LOGIN_URL, data: {
				'username':username,
				'password':password,
				'rememberMe': 1
			});
			print(response.data);
			UserProfileEntity userProfileEntity = UserProfileEntity().fromJson(response.data);
			print(response.headers['authorization'][0]);
			SharedPreferences preferences = await SharedPreferences.getInstance();
			preferences.setString('username', username);
			preferences.setInt('id', userProfileEntity.user.id);
			preferences.setString('nickname', userProfileEntity.user.profile.nickname);
			preferences.setInt('sex', userProfileEntity.user.profile.sex);
			preferences.setString('motto', userProfileEntity.user.profile.motto);
			preferences.setString("token", response.headers['authorization'][0]);
			preferences.setBool('isLogin', true);
			print("prefer restore success");
			print(preferences.get('account'));
//			UserProfileEntity userProfileEntity = new UserProfileEntity().fromJson(response.data);
//			print(userProfileEntity);
			return null;
		}on DioError catch(e){
			print(e.response.statusCode);
			if(e.response.statusCode == 401)
				return "用户名或密码错误";
			else if(e.response.statusCode == 404)
				return "网络开小差了哦";
			else
				return "发生未知错误了哦";
		}

	}

	Future<String> _recoverPassword(String name) {
//		Response response = await Dio().get(LOGIN_URL);
//		if(response.statusCode == 200){
//			return "login success";
//		}else{
//			return "login error";
//		}
//		});
	}

	@override
	Widget build(BuildContext context) {
		final inputBorder = BorderRadius.vertical(
			bottom: Radius.circular(10.0),
			top: Radius.circular(20.0),
		);

		return Scaffold(

			body:

					FlutterLogin(

						title: "Dustbin Verify",
						logo: 'assets/images/ic_launcher.png',
						logoTag: 'near.huscarl.loginsample.logo',
						titleTag: 'near.huscarl.loginsample.title',
						 messages: LoginMessages(
						   usernameHint: '电子邮件地址',
						   passwordHint: '密码',
						   confirmPasswordHint: '确定密码',
						   loginButton: '登陆',
						   signupButton: '注册',
						   forgotPasswordButton: '忘记密码?',
						   recoverPasswordButton: '找回密码',
						   goBackButton: '返回',
						   confirmPasswordError: '两次输入密码不一致!',
						   recoverPasswordIntro: '不要伤心，一切都会好起来的。(^.^)',
						   recoverPasswordDescription: '即将发送验证邮件到您的邮箱。(0.0)',
						   recoverPasswordSuccess: '密码修改成功',
						 ),
						// theme: LoginTheme(
						//   primaryColor: Colors.teal,
						//   accentColor: Colors.yellow,
						//   errorColor: Colors.deepOrange,
						//   pageColorLight: Colors.indigo.shade300,
						//   pageColorDark: Colors.indigo.shade500,
						//   titleStyle: TextStyle(
						//     color: Colors.greenAccent,
						//     fontFamily: 'Quicksand',
						//     letterSpacing: 4,
						//   ),
						//   // beforeHeroFontSize: 50,
						//   // afterHeroFontSize: 20,
						//   bodyStyle: TextStyle(
						//     fontStyle: FontStyle.italic,
						//     decoration: TextDecoration.underline,
						//   ),
						//   textFieldStyle: TextStyle(
						//     color: Colors.orange,
						//     shadows: [Shadow(color: Colors.yellow, blurRadius: 2)],
						//   ),
						//   buttonStyle: TextStyle(
						//     fontWeight: FontWeight.w800,
						//     color: Colors.yellow,
						//   ),
						//   cardTheme: CardTheme(
						//     color: Colors.yellow.shade100,
						//     elevation: 5,
						//     margin: EdgeInsets.only(top: 15),
						//     shape: ContinuousRectangleBorder(
						//         borderRadius: BorderRadius.circular(100.0)),
						//   ),
						//   inputTheme: InputDecorationTheme(
						//     filled: true,
						//     fillColor: Colors.purple.withOpacity(.1),
						//     contentPadding: EdgeInsets.zero,
						//     errorStyle: TextStyle(
						//       backgroundColor: Colors.orange,
						//       color: Colors.white,
						//     ),
						//     labelStyle: TextStyle(fontSize: 12),
						//     enabledBorder: UnderlineInputBorder(
						//       borderSide: BorderSide(color: Colors.blue.shade700, width: 4),
						//       borderRadius: inputBorder,
						//     ),
						//     focusedBorder: UnderlineInputBorder(
						//       borderSide: BorderSide(color: Colors.blue.shade400, width: 5),
						//       borderRadius: inputBorder,
						//     ),
						//     errorBorder: UnderlineInputBorder(
						//       borderSide: BorderSide(color: Colors.red.shade700, width: 7),
						//       borderRadius: inputBorder,
						//     ),
						//     focusedErrorBorder: UnderlineInputBorder(
						//       borderSide: BorderSide(color: Colors.red.shade400, width: 8),
						//       borderRadius: inputBorder,
						//     ),
						//     disabledBorder: UnderlineInputBorder(
						//       borderSide: BorderSide(color: Colors.grey, width: 5),
						//       borderRadius: inputBorder,
						//     ),
						//   ),
						//   buttonTheme: LoginButtonTheme(
						//     splashColor: Colors.purple,
						//     backgroundColor: Colors.pinkAccent,
						//     highlightColor: Colors.lightGreen,
						//     elevation: 9.0,
						//     highlightElevation: 6.0,
						//     shape: BeveledRectangleBorder(
						//       borderRadius: BorderRadius.circular(10),
						//     ),
						//     // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
						//     // shape: CircleBorder(side: BorderSide(color: Colors.green)),
						//     // shape: ContinuousRectangleBorder(borderRadius: BorderRadius.circular(55.0)),
						//   ),
						// ),
						emailValidator: (value) {
							if (!value.contains('@') || !value.endsWith('.com')) {
								return "邮件必须包含 '@' 和以'.com'结尾";
							}
							return null;
						},
						passwordValidator: (value) {
							if (value.isEmpty) {
								return '密码还没填哦';
							}
							return null;
						},
						onLogin: (loginData) {
							print('Login info');
							print('Name: ${loginData.name}');
							print('Password: ${loginData.password}');
							return _login(loginData.name,loginData.password);
						},
						onSignup: (loginData) {
							print('Signup info');
							print('Name: ${loginData.name}');
							print('Password: ${loginData.password}');
//				return _loginUser(loginData);
							return null;
						},
						onSubmitAnimationCompleted: () {
							Navigator.pop(context);
							return;
						},
						onRecoverPassword: (name) {
							print('Recover password info');
							print('Name: $name');
//				return _recoverPassword(name);
							return;
							// Show new password dialog
						},
//						showDebugButtons: true,
					)


		);
	}

}
